package main

import (
	"io/ioutil"
	"os"
	"os/exec"
	"sdk/linkageclient"
	"sdk/sdkinterface"
	"sdk/sdklog"
	"sdk/shell"
	"sdk/utils"
	"strings"
)

var (
	g_loger      *sdklog.Logger          = sdklog.New("main: ")
	g_la_session sdkinterface.Sessionner = nil
)

func main() {
	//初始化一个联动会话
	g_loger.Debug("enter main")
	g_la_session = linkageclient.GetInstance()
	g_la_session.Init()
	go g_la_session.Run()

	//加个命令行
	shell_run()
}

func shell_run() {
	//注册控制命令节点
	shell.RegisterElement("command")
	//注册命令
	shell.RegisterCmd("command", "fmt", goFmtAll)
	//注册配置命令节点
	shell.RegisterElement("conf")
	shell.Run(os.Stdin)
}

//给所有*.go文件格式化一下
func goFmtAll(v ...interface{}) bool {
	cur_dir := utils.GetExePath()
	goFmtDir(cur_dir)

	return true
}

func goFmtDir(dir string) {
	fileinfo, err := ioutil.ReadDir(dir)

	if err != nil {
		g_loger.Debug("readdir ", dir, " failed ")
		return
	}

	for _, file := range fileinfo {
		fileName := dir + "/" + file.Name()
		if file.IsDir() {
			goFmtDir(fileName)
		} else {
			if strings.HasSuffix(file.Name(), "go") {
				g_loger.Debug("fmt ", fileName)
				cmd := exec.Command("go", "fmt", fileName)
				cmd.Stdout = sdklog.LogWriter()
				cmd.Run()
			}
		}
	}
}
